package com.example.moonshine.baidumap.View.Fragment;


import android.annotation.SuppressLint;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;

import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


import com.example.moonshine.baidumap.Entity.GpsRrsultCodeData;
import com.example.moonshine.baidumap.Entity.TaskInfoData;
import com.example.moonshine.baidumap.Entity.TaskInfoRrsultData;
import com.example.moonshine.baidumap.R;
import com.example.moonshine.baidumap.Service.FragmentService;
import com.example.moonshine.baidumap.Util.FalseDialog;
import com.example.moonshine.baidumap.Util.HttpUtil;
import com.example.moonshine.baidumap.Util.SureDialog;
import com.example.moonshine.baidumap.Util.UrlHttpData;
import com.example.moonshine.baidumap.Util.publicUtil;
import com.example.moonshine.baidumap.View.Activity.BroadCastManager;
import com.example.moonshine.baidumap.View.Activity.DetaialActivity;
import com.example.moonshine.baidumap.View.Activity.NavigationActivity;
import com.github.zackratos.ultimatebar.UltimateBar;
import com.google.gson.Gson;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static android.content.ContentValues.TAG;


public class FirstFragment extends Fragment {

    View view;
    ArrayList postlist = new ArrayList();
    RefreshLayout refreshLayout;
    PostAdapter postAdapter;
    ListView listView;
    String token = null;
    String name = null;
    int judgeTaskCode = 1;
    Handler handler;

    //    private LocalReceiver mReceiver;
//    @Override
//    public void onAttach(Context context) {
//        super.onAttach(context);
//        try {
//            IntentFilter filter = new IntentFilter();
//            filter.addAction("fragment_home_left");
//            mReceiver = new LocalReceiver();
//            BroadCastManager.getInstance().registerReceiver(getActivity(), mReceiver, filter);//注册广播接收者
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//    class LocalReceiver extends BroadcastReceiver{
//
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            //收到广播后的处理
//            String orderid = intent.getStringExtra("order");
//        }
//
//    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fg1, container, false);
        listView = view.findViewById(R.id.listview);
        refreshLayout = (RefreshLayout) view.findViewById(R.id.refreshLayout);
        handler = new Handler();
        setDownRefresh(getContext(), refreshLayout);
        initView();
        return view;
    }

    public void initView() {

        //获取token，name
        publicUtil publicUtil = new publicUtil();
        name = publicUtil.getUserInfo(getContext(), "username", "login");
        token = publicUtil.getUserInfo(getContext(), "token", "token");
        TaskInfoData.taskInfo infodata = new TaskInfoData.taskInfo("2", "贵阳市白云区云城尚品一号井", "2018-11-01 13:30:30", "106.656504,26.681777", "1", "21");
        postlist.add(infodata);

        // 异步查询
        new Thread(new Runnable() {
            @Override
            public void run() {
                new AnotherTask().execute("");
            }
        }).start();

//
        postAdapter = new PostAdapter(getContext(), postlist);
        listView.setAdapter(postAdapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //我们需要的内容，跳转页面或显示详细信息
                if (position < 1) {
                    startActivity(new Intent(getActivity(), DetaialActivity.class));
                    Log.i("tag", "被点击了");
                }
            }
        });
        postAdapter = new PostAdapter(getContext(), postlist);
        listView.setAdapter(postAdapter);
    }


    public class PostAdapter extends BaseAdapter {

        private ArrayList<TaskInfoData.taskInfo> List;
        private Context context;

        PostAdapter(Context context, ArrayList<TaskInfoData.taskInfo> list) {
            this.context = context;
            this.List = list;
        }

        @Override
        public int getCount() {
            return List.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @SuppressLint("SetTextI18n")
        @Override
        public View getView(final int position, View view, ViewGroup viewGroup) {
            if (judgeTaskCode == 1) {
                if (view == null) {
                    view = View.inflate(context, R.layout.task_item_out, null);
                }
                TextView tv = view.findViewById(R.id.item_bianhao);
                TextView tv1 = view.findViewById(R.id.item_guzhang);
                TextView tv2 = view.findViewById(R.id.item_time);

//                TaskInfoData.taskInfo taskInfo = List.get(position).getTaskInfo();
//                tv.setText(List.get(position).getEventType());
//                tv1.setText(List.get(position).getGpsPosition());
//                tv2.setText(List.get(position).getFailureTime().substring(0, 9));
                Button fasebtn = (Button) view.findViewById(R.id.false_btn);
                Button surebtn = (Button) view.findViewById(R.id.sure_btn);
                fasebtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
//                        falseDialog();
                    }
                });
                surebtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        /**
                         * 点击接受 请求数据
                         */
                        setAcceptTask();
                    }
                });
            } else {
                if (view == null) {
                    view = view.inflate(context, R.layout.task_item, null);
                }
                TextView tv = view.findViewById(R.id.item_bianhao);
                TextView tv1 = view.findViewById(R.id.item_guzhang);
                TextView tv2 = view.findViewById(R.id.item_time);

//                TaskInfoData.taskInfo taskInfo = List.get(position).getTaskInfo();
//                tv.setText(List.get(position).getEventType());
//                tv1.setText(List.get(position).getGpsPosition());
//                tv2.setText(List.get(position).getFailureTime().substring(0, 9));
                Button button1 = view.findViewById(R.id.gps_btn);
                final Button button2 = view.findViewById(R.id.item_remove);
                button1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent();
                        intent.setClass(getActivity(), NavigationActivity.class);
                        startActivity(intent);
                    }
                });
                new Handler().postDelayed(new Runnable() {
                @Override
                  public void run() {

                         button2.setEnabled(true);

                           }}, 1000);    //延时1s执行

                button2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        // 完成任务
                        setFinishTask();
                    }
                });

            }
            return view;
        }
    }


    /**
     * Fragment下拉刷新
     *
     * @param context
     * @param refreshLayout
     */
    public void setDownRefresh(Context context, RefreshLayout refreshLayout) {

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshlayout) {

                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
//                init();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshlayout) {
                refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
            }
        });
        refreshLayout.setRefreshHeader(new MaterialHeader(context));
        refreshLayout.setRefreshFooter(new ClassicsFooter(context));
    }
//
//
//    @Override
//    public void onStart() {
//        super.onStart();
//
//
//    }
//
//    @Override
//    public void onResume() {
//        super.onResume();
///    setDownRefresh(getContext(),refreshLayout);
//    }

//
//    /**
//     * 接收广播后的处理
//     */
////    class LocalReceiver extends BroadcastReceiver {
////
////        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
////        @Override
////        public void onReceive(Context context, Intent intent) {
////            //收到广播后的处理
////            String text = intent.getStringExtra("text");
////            try {
////                if (text.equals("102")) {
////                    judgeTaskCode = 1;
////                    initView();
////                } else if (text.equals("1")) {
////                    judgeTaskCode = 1;
////                    showDialog();
////                } else if (text.equals("2")) {
////                    judgeTaskCode = 2;
////                }
////                else if (text.equals("5")) {
////                    getActivity().onBackPressed();
////                    Log.i(TAG, "finish");
////
////                }else if (text.equals("logout"))
////                {
////                    intent.putExtra("textresult","3");
////                    intent.setAction("fragment_home");
////                    BroadCastManager.getInstance().sendBroadCast(getActivity(), intent);
////                    showNoProject();//挤下线
////                }
////
////            } catch (Exception e) {
////                e.printStackTrace();
////            }
////            Log.i("tag", "传参的数字为" + text);
////        }
////    }
////
////

    ////
////    public void init() {
////        postlist.clear();
////        new Thread(new Runnable() {
////            @Override
////            public void run() {
////                new AnotherTask().execute("");
////            }
////        }).start();
////    }
////
////
    @SuppressLint("StaticFieldLeak")
    private class AnotherTask extends AsyncTask<String, Void, String> {
        @Override
        protected void onPostExecute(String result) {
            //对UI组件的更新操作
            Gson gson = new Gson();

            Log.i("tag", "请求结果:" + result);
            try {
                TaskInfoRrsultData taskInfoData = gson.fromJson(result, TaskInfoRrsultData.class);
                Log.i("tag", "taskInfoData:" + taskInfoData.getTaskInfo());
                if (taskInfoData.getTaskInfo() == null) {
                    Toast.makeText(getActivity(), "没有任务", Toast.LENGTH_SHORT).show();

                    return;
                } else {
//                    TaskInfoData.taskInfo  taskInfo = taskInfoData.getTaskInfo();
//                    String eventType = taskInfo.getEventType();
//                    String gpsPosition = taskInfo.getFailureTime();
//                    String failureTime = taskInfo.getFailureTime();
//                    String faultGpsId = taskInfo.getFaultGpsId();
//                    String eventId = taskInfo.getEventId();
//                    String state =  taskInfo.getState();
//                    TaskInfoData.taskInfo infodata = new TaskInfoData.taskInfo(eventType,gpsPosition,failureTime,faultGpsId,eventId,state);
//                    postlist.add(infodata);
//                    publicUtil publicUtil = new publicUtil();
//                    publicUtil.saveInfo(getContext(),"gps",gpsPosition,"token");
//                    Log.i("tag", "值为：" + postlist.get(0));
                }
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(getContext(), "请求错误", Toast.LENGTH_SHORT).show();
            }
            try {
                postAdapter.notifyDataSetChanged();
            } catch (Exception e) {
                Log.e(TAG, "postlisthttp: ", e);
            }
        }

        @Override
        protected String doInBackground(String... params) {
            //耗时的操作
            UrlHttpData urlHttpData = new UrlHttpData();
            OkHttpClient client = new OkHttpClient();
            FormBody body = new FormBody.Builder()
                    .add("username", name)
                    .build();
            Request request = new Request.Builder()
                    .addHeader("accessToken", token)
                    .url(urlHttpData.seeTaskUrl)
                    .post(body)
                    .build();
            String result = "";
            try {
                Response response = client.newCall(request).execute();
                //获取后台传输的额status状态码
                result = response.body().string();
            } catch (IOException e) {
                e.printStackTrace();
                Log.e(TAG, "doInBackground: ", e);
            }
            return result;
        }
    }


    /**
     * 任务接收
     */
    public void setAcceptTask() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                Log.d("PostAdapter", "被点击了");
//                UrlHttpData urlHttpData = new UrlHttpData();
//                HttpUtil httpUtil = new HttpUtil();
                try {
                    String code =getpost();
                    if (code.equals("1")) {
                        Toast.makeText(getContext(), "任务接受成功，请赶紧完成任务", Toast.LENGTH_SHORT).show();
                        //发送广播
                        new Thread() {
                            @Override
                            public void run() {
                                handler.post(runnable);//子线程更新ui时，当子线程需要更新UI时，发消息通知主线程并将更新UI的任务post给主线程，让主线程来完成分内的UI更新操作
                            }
                        }.start();
                        //设置选择item的类型
                        judgeTaskCode = 2;
                    } else {
                        Toast.makeText(getContext(), "请求超时，请重试", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(getContext(), "服务器故障", Toast.LENGTH_SHORT).show();
                }
                Looper.loop();
            }
        }).start();
    }

    /**
     * 任务完成
     */
    public void setFinishTask() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
//                String result = httpUtil.getPostFinishTask(name, token, urlHttpData.completeTask);
//                Gson gson = new Gson();
//                GpsRrsultCodeData gpsRrsultCodeData = gson.fromJson(result, GpsRrsultCodeData.class);
//                String code = gpsRrsultCodeData.getState();
                String code =getpost();
                if (code.equals("1")) {

                    Log.i("PostAdapter", "成功");
                    Toast.makeText(getActivity(), "任务已完成", Toast.LENGTH_SHORT).show();
                    new Thread() {
                        @Override
                        public void run() {
                            handler.post(runnableUi);//子线程更新ui时，当子线程需要更新UI时，发消息通知主线程并将更新UI的任务post给主线程，让主线程来完成分内的UI更新操作
                        }
                    }.start();
////
                } else {
                    Toast.makeText(getActivity(), "失败", Toast.LENGTH_LONG).show();
                }
                Looper.loop();
            }
        }).start();
    }

    public String getpost(){
        HttpUtil httpUtil = new HttpUtil();
        UrlHttpData urlHttpData = new UrlHttpData();
        String rusult = httpUtil.getPostAcceptTask(name, "1", "2", token, urlHttpData.receiveTaskUrl);
        Gson gson = new Gson();
        GpsRrsultCodeData gpsRrsultCodeData = gson.fromJson(rusult, GpsRrsultCodeData.class);
        String code = gpsRrsultCodeData.getState();
        return code;
    }

    /**
     * 建立子线程的传递ui给主线程修改
     */
    Runnable runnableUi = new Runnable() {
        @Override
        public void run() {
            //更新界面
            postlist.clear();
            postAdapter.notifyDataSetChanged();
        }

    };

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            //更新界面
            postlist.clear();
            initView();
        }
    };
}




////    };
////
////    @Override
////    public void onStart() {
////        super.onStart();
////        initView();
////        //接收广播
////        /**
////         * 注册广播接收
////         */
////        try {
////            IntentFilter filter = new IntentFilter();
////            filter.addAction("fragment_home_left");
////            mReceiver = new LocalReceiver();
////            BroadCastManager.getInstance().registerReceiver(getActivity(), mReceiver, filter);//注册广播接收者
////        } catch (Exception e) {
////            e.printStackTrace();
////        }
////
////
////    }
////
////
////    //    private boolean isGetData = false;
//////    @Override
//////    public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
//////        //   进入当前Fragment
//////        if (enter && !isGetData) {
//////            isGetData = true;
//////            //   这里可以做网络请求或者需要的数据刷新操作
//////            postlist.clear();
//////            initView();
//////        } else {
//////            isGetData = false;
//////        }
//////        return super.onCreateAnimation(transit, enter, nextAnim);
//////    }
//////
//////    @Override
//////    public void onResume() {
//////        super.onResume();
//////        if (!isGetData) {
//////            //   这里可以做网络请求或者需要的数据刷新操作
////////            postlist.clear();
////////            initView();
//////            isGetData = true;
//////        }
//////    }
//////
//////    @Override
//////    public void onPause() {
//////        super.onPause();
//////        isGetData = false;
//////    }
//    public void showDialog() {
//        final SureDialog Dialog = new SureDialog(getContext());
//        Dialog.setCanceledOnTouchOutside(true);
//        Dialog.setTitle("消息提示");
//        Dialog.setYesOnclickListener("确定", new SureDialog.onYesOnclickListener() {
//            @Override
//            public void onYesClick() {
//                Log.i(TAG, "点击了确定");
////                new Thread(new Runnable() {
////                    @Override
////                    public void run() {
////                        Looper.prepare();
////                        DialogHtttpMap dialogHtttpMap = new DialogHtttpMap();
////                        try {
////                            String rusult = dialogHtttpMap.DialogSurehttp(token, MsgStaticdata.getManholeId());
////                            if (rusult.equals("10")) {
////                                Toast.makeText(getContext(), "任务接受成功，请赶紧完成任务", Toast.LENGTH_SHORT).show();
////                                //发送广播
////                                judgeTaskCode = 2;
////                                new Thread() {
////                                    @Override
////                                    public void run() {
////                                        handler.post(runnable);//子线程更新ui时，当子线程需要更新UI时，发消息通知主线程并将更新UI的任务post给主线程，让主线程来完成分内的UI更新操作
////                                    }
////                                }.start();
////
////                            } else {
////                                Toast.makeText(getContext(), "请求超时，请重试", Toast.LENGTH_SHORT).show();
////                            }
////                        } catch (Exception e) {
////                            e.printStackTrace();
////                            Toast.makeText(getContext(), "服务器故障", Toast.LENGTH_SHORT).show();
////                        }
////                        Looper.loop();
////                    }
////                }).start();
//                Dialog.dismiss();
//            }
//        });
//        Dialog.setNoOnclickListener("取消", new SureDialog.onNoOnclickListener() {
//            @Override
//            public void onNoClick() {
//                falseDialog();
//                Dialog.dismiss();
//            }
//        });
//        Dialog.show();
//    }
//
//    public void falseDialog() {
//        final FalseDialog Dialog = new FalseDialog(getContext());
//        Dialog.setCanceledOnTouchOutside(true);
//        Dialog.setTitle("消息提示");
//        Dialog.setYesOnclickListener("确定", new FalseDialog.onYesOnclickListener() {
//            @Override
//            public void onYesClick() {
////
////                    final String Message = Dialog.getMessage();
////                    //执行网络请求，拒绝请求
////                    new Thread(new Runnable() {
////                        @Override
////                        public void run() {
////                            Looper.prepare();
////                            DialogHtttpMap dialogHtttpMap = new DialogHtttpMap();
////                            try {
////                                String result = dialogHtttpMap.DialogNohttp(token, MsgStaticdata.getManholeId(), StaticUser.getUser(), Message);
////                                if (result.equals("10")) {
////                                    Toast.makeText(getContext(), "提交成功", Toast.LENGTH_SHORT).show();
////                                    Log.i(TAG, "提交成功");
////                                    new Thread() {
////                                        @Override
////                                        public void run() {
////                                            handler.post(runnableUi);//子线程更新ui时，当子线程需要更新UI时，发消息通知主线程并将更新UI的任务post给主线程，让主线程来完成分内的UI更新操作
////                                        }
////                                    }.start();
////                                } else {
////                                    Toast.makeText(getContext(), "网络超时，请重试", Toast.LENGTH_SHORT).show();
////                                }
////                            } catch (Exception e) {
////                                e.printStackTrace();
////                                Toast.makeText(getContext(), "服务器故障", Toast.LENGTH_SHORT).show();
////                            }
////                            Looper.loop();
////                        }
////                    }).start();
//                Dialog.dismiss();
//
//            }
//        });
//        Dialog.setNoOnclickListener("取消", new FalseDialog.onNoOnclickListener() {
//            @Override
//            public void onNoClick() {
//                showDialog();
//                Dialog.dismiss();
//            }
//        });
//        Dialog.show();
//    }
//
//
//
//}
//
//    public void postfinsh() {
//        handler1 = new Handler();
//        runnable1 = new Runnable() {
//            @Override
//            public void run() {
//                // TODO Auto-generated method stub
//                //要做的事情
//                DELAY_TIME=DELAY_TIME+1;
//                Log.i(TAG, "time为："+DELAY_TIME);
//                if (DELAY_TIME>10)
//                {
//                    handler1.removeCallbacks(runnable1);
//                    return;
//                }
//                handler1.postDelayed(this, 2000);
//            }
//        };
//        handler1.postDelayed(runnable1, 2000);
//    }
//
//
//    public void showNoProject() {
//        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
//                .setMessage("你的账号已在另一客户端登录，你已下线，请重新登录!")
//                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        Intent intent = new Intent();
//                        intent.setClass(getActivity(), LaunchActivity.class);
//                        startActivity(intent);
//                        dialog.dismiss();
//
//                    }
//                });
//        builder.setCancelable(false);
//        builder.show();
//    }
//}
